package com.fqgj.sentry.interceptors;

import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.sentry.common.annotations.VisitorAccessible;
import com.fqgj.sentry.common.cache.RedisUserInfo;
import com.fqgj.sentry.common.cache.RequestLocalInfo;
import com.fqgj.sentry.common.exception.BizException;
import com.fqgj.sentry.common.exception.enums.ErrorCodeEnums;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: yujianfu (mr.vencnet@gmail.com)
 * Date: 16/9/5
 * Time: 下午2:27
 */
@Component
public class UserAccessRightInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisClient redisClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,remember-me,bid,accessToken");

        String accessToken = request.getHeader("accessToken");
        if (StringUtils.isEmpty(accessToken)) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            VisitorAccessible annotation = handlerMethod.getMethodAnnotation(VisitorAccessible.class);
            if (annotation != null) {
                return true;
            }
            if (!request.getMethod().equals("OPTIONS")) {
                if (!handlerMethod.getMethod().getName().toUpperCase().equals("LOGIN")) {
                    throw new BizException(ErrorCodeEnums.no_access_right, "需要登陆才能访问");
                }
            }
        } else {
            if (!hasPermission(accessToken)) {
                throw new BizException(ErrorCodeEnums.no_access_right, "请重新登录");
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

    private Boolean hasPermission(String accessToken) {
        if (accessToken.indexOf(";") == -1 || accessToken.indexOf("appCode=") == -1) {
            throw new BizException(ErrorCodeEnums.app_not_exist_error, "请选择应用");
        }
        String token = accessToken.substring(0, accessToken.indexOf(";"));
        String appCode = accessToken.substring(accessToken.indexOf("appCode=") + 8, accessToken.length());
        if (StringUtils.isNotEmpty(appCode)) {
            RequestLocalInfo.putCurrentAppCode(appCode);
        }
        if (StringUtils.isBlank(token)) {
            throw new BizException(ErrorCodeEnums.access_expire, "请重新登录");
        }
        RedisUserInfo redisUserInfo = (RedisUserInfo) redisClient.get(token);
        if (null == redisUserInfo) {
            return false;
        }
        RequestLocalInfo.putCurrentUser(redisUserInfo);
        RequestLocalInfo.putCurrentUserId(redisUserInfo.getUserId());
        RequestLocalInfo.putCurrentMerchantId(redisUserInfo.getMerchantId());
        return true;
    }


}
